package com.kanshu.ksgb.fastread.doudou.common.business.ad

import android.app.Activity
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean
import com.kanshu.ksgb.fastread.doudou.common.util.Utils
import com.qq.e.ads.banner.ADSize
import com.qq.e.ads.banner.AbstractBannerADListener
import com.qq.e.ads.banner.BannerView
import com.qq.e.ads.nativ.NativeExpressAD
import com.qq.e.ads.nativ.NativeExpressADView
import com.qq.e.ads.splash.SplashAD
import com.qq.e.ads.splash.SplashADListener
import com.qq.e.comm.util.AdError

/**
 * Title:
 * Description:
 * Copyright: Copyright(c)2018
 * Company: 看书网
 * CreateTime: 2018/5/16 17:56
 *
 * @author EvanHe
 * @version 3.0
 */
class GdtAdUtils {

    companion object {


        /**
         * 拉取开屏广告，开屏广告的构造方法有3种，详细说明请参考开发者文档。
         *
         * @param activity      展示广告的activity
         * @param container   展示广告的大容器
         * @param skipContainer 自定义的跳过按钮：传入该view给SDK后，SDK会自动给它绑定点击跳过事件。SkipView的样式可以由开发者自由定制，其尺寸限制请参考activity_splash.xml或者接入文档中的说明。
         * @param adListener    广告状态监听器
         */
        fun fetchSplashAd(activity: Activity, container: ViewGroup?, skipContainer: View?, adConfig: ADConfigBean, adListener: BaseAdListener?) {
            val adContainer = container ?: FrameLayout(activity)
            val splashId = adConfig.ad_position_id
            if (adListener is SplashAdListener) {
                SplashAD(activity, adContainer, skipContainer, activity.getString(R.string.ad_gdt_app_id), splashId, object : SplashADListener {
                    override fun onADExposure() {
                        Log.i("gdt_Splash", "onADExposure: ")
                    }

                    override fun onADDismissed() {
                        Log.i("gdt_Splash", "onADDismissed")
                        adListener.onADClosed()
                    }

                    override fun onNoAD(adError: AdError) {
                        Log.i("gdt_Splash", "onNoAD: ${adError.errorCode} ${adError.errorMsg}")
                        adListener.onAdLoadFailed()
                    }

                    override fun onADPresent() {
                        Log.i("gdt_Splash", "onAdLoadSucceeded")
                        skipContainer?.isEnabled = false
                        adListener.onAdLoadSucceeded(adContainer)
                        adListener.isShowSkipView(true)
                        AdUtils.pVUVAd(AdPresenter.AD_SHOW, adConfig)
                    }

                    override fun onADClicked() {
                        Log.i("gdt_Splash", "onADClicked")
                        adListener.onAdClicked()
                        AdUtils.pVUVAd(AdPresenter.AD_CLICK, adConfig)
                    }

                    override fun onADTick(l: Long) {
                        Log.i("gdt_Splash", "onADTick")
                        adListener.onADTick(l)
                    }
                }, 0)
            }
        }

        fun fetchBannerAd(activity: Activity, container: ViewGroup?, adConfig: ADConfigBean, adListener: BaseAdListener?) {
            val adContainer = container ?: FrameLayout(activity)
            val bv = BannerView(activity, ADSize.BANNER, activity.getString(R.string.ad_gdt_app_id), adConfig.ad_position_id)
            // 注意：如果开发者的banner不是始终展示在屏幕中的话，请关闭自动刷新，否则将导致曝光率过低。
            // 并且应该自行处理：当banner广告区域出现在屏幕后，再手动loadAD。
            bv.setRefresh(31)
            var isClickAd = true

            bv.setADListener(object : AbstractBannerADListener() {
                override fun onNoAD(error: AdError) {
                    Log.i("gdt_banner", String.format("Banner onNoAD，eCode = %d, eMsg = %s", error.errorCode, error.errorMsg))
                    adListener?.onAdLoadFailed()
                    AdUtils.pVUVAd(AdPresenter.AD_REQUEST, adConfig)
                }

                override fun onADReceiv() {
                    Log.i("gdt_banner", "ONBannerReceive")
                    if (isClickAd) {
                        adContainer.tag = bv
                        adListener?.onAdLoadSucceeded(adContainer)
                    }
                    AdUtils.pVUVAd(AdPresenter.AD_REQUEST, adConfig)
                }

                override fun onADExposure() {
                    Log.i("gdt_banner", "onADExposure")
                    AdUtils.pVUVAd(AdPresenter.AD_SHOW, adConfig)
                }

                override fun onADClicked() {
                    Log.i("gdt_banner", "onADClicked")
                    adListener?.onAdClicked()
                    isClickAd = false
                    AdUtils.pVUVAd(AdPresenter.AD_CLICK, adConfig)
                }
            })
            AdUtils.destroyAd(adContainer)
            adContainer.removeAllViews()
            adContainer.addView(bv)
            bv.loadAD()
        }

        fun fetchNativeAd(activity: Activity, container: ViewGroup?, adConfig: ADConfigBean, adStyle: Int, layout: Int, adListener: BaseAdListener?, adCount: Int) {
            val adContainer: ViewGroup = when (adStyle) {
                AdStyleBean.BOOK_COVER_STYLE -> {
                    if (layout > 0) {
                        val view = LayoutInflater.from(activity).inflate(layout, container, false)
                        val cover: ImageView = view.findViewById(R.id.cover) as ImageView
                        cover.visibility = View.GONE
                        val title = view.findViewById(R.id.book_title) as TextView?
                        val desc = view.findViewById(R.id.desc) as TextView?
                        title?.text = adConfig.title ?: ""
                        desc?.text = adConfig.description ?: ""
                        desc?.visibility = View.VISIBLE
                        view.findViewById(R.id.ad_container) as ViewGroup
                    } else {
                        container ?: FrameLayout(activity)
                    }
                }
                else -> container ?: FrameLayout(activity)
            }
            val adSize = com.qq.e.ads.nativ.ADSize(com.qq.e.ads.nativ.ADSize.FULL_WIDTH, com.qq.e.ads.nativ.ADSize.AUTO_HEIGHT) // 消息流中用AUTO_HEIGHT
            val nativeAd = NativeExpressAD(activity, adSize, activity.getString(R.string.ad_gdt_app_id),  adConfig.ad_position_id, object : NativeExpressAD.NativeExpressADListener {
                override fun onNoAD(adError: AdError) {
                    Log.i("gdt_native", String.format("onNoAD, error code: %d, error msg: %s", adError.errorCode, adError.errorMsg))
                    //mShelfPresenter.getContentInfo(false)
                    adListener?.onAdLoadFailed()
                }

                override fun onADLoaded(adList: List<NativeExpressADView>) {
                    Log.i("gdt_native", "onADLoaded: " + adList.size)
                    if (!Utils.isEmptyList<NativeExpressADView>(adList)) {
                        val adView = adList[0]
                        if (adContainer.childCount > 0) {
                            AdUtils.destroyAd(adContainer)
                            adContainer.removeAllViews()
                        }
                        adContainer.tag = adView
                        adContainer.addView(adView)
                        adView.render()
                        if (AdStyleBean.BOOK_COVER_STYLE == adStyle) {
                            adListener?.onAdLoadSucceeded(getRootView(adContainer))
                        } else {
                            adListener?.onAdLoadSucceeded(adContainer)
                        }
                    }
                }

                override fun onRenderFail(adView: NativeExpressADView) {
                    Log.i("gdt_native", "onRenderFail: " + adView.toString())
                }

                override fun onRenderSuccess(adView: NativeExpressADView) {
                    Log.i("gdt_native", "onRenderSuccess: " + adView.toString())
                }

                override fun onADExposure(adView: NativeExpressADView) {
                    Log.i("gdt_native", "onADExposure: " + adView.toString())
                    AdUtils.pVUVAd(AdPresenter.AD_SHOW, adConfig)
                }

                override fun onADClicked(adView: NativeExpressADView) {
                    Log.i("gdt_native", "onADClicked: " + adView.toString())
                    adListener?.onAdClicked()
                    AdUtils.pVUVAd(AdPresenter.AD_CLICK, adConfig)
                }

                override fun onADClosed(adView: NativeExpressADView) {
                    Log.i("gdt_native", "onADClosed: " + adView.toString())
                    adListener?.onADClosed()
                }

                override fun onADLeftApplication(adView: NativeExpressADView) {
                    Log.i("gdt_native", "onADLeftApplication: " + adView.toString())
                }

                override fun onADOpenOverlay(adView: NativeExpressADView) {
                    Log.i("gdt_native", "onADOpenOverlay: " + adView.toString())
                }

                override fun onADCloseOverlay(adView: NativeExpressADView) {
                    Log.i("gdt_native", "onADOpenOverlay: " + adView.toString())
                }

            })
            nativeAd.loadAD(adCount)
        }

        /* fun destroyAd(adContainer: FrameLayout) {
             if (adContainer.childCount > 0) {
                 val view = adContainer.getChildAt(0)
                 if (view is NativeExpressADView) {
                     view.destroy()
                 }
                 adContainer.removeAllViews()
             }
         }*/
    }
}